import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    token: null,
    isAuthenticated: false,
    expiresAt: null
  }),
  
  getters: {
    getUserInfo: (state) => state.user,
    isLoggedIn: (state) => {
      if (!state.isAuthenticated || !state.expiresAt) return false;
      
      // 检查是否过期
      return state.isAuthenticated && new Date().getTime() < state.expiresAt;
    },
    getToken: (state) => state.token
  },
  
  actions: {
    setUser(userData) {
      this.user = userData;
      this.token = userData.token;
      this.isAuthenticated = true;
      this.expiresAt = userData.expiresAt || null;
      
      // 将数据保存到 localStorage，以便页面刷新后保持登录状态
      localStorage.setItem('user', JSON.stringify(userData));
      localStorage.setItem('token', userData.token);
      localStorage.setItem('expiresAt', userData.expiresAt || '');
    },
    
    logout() {
      this.user = null;
      this.token = null;
      this.isAuthenticated = false;
      this.expiresAt = null;
      
      // 清除本地存储的数据
      localStorage.removeItem('user');
      localStorage.removeItem('token');
      localStorage.removeItem('expiresAt');
    },
    
    initUserFromStorage() {
      const userString = localStorage.getItem('user');
      const token = localStorage.getItem('token');
      const expiresAt = localStorage.getItem('expiresAt') ? parseInt(localStorage.getItem('expiresAt')) : null;
      
      if (userString && token) {
        try {
          // 检查是否过期
          if (expiresAt && new Date().getTime() > expiresAt) {
            console.log('用户登录已过期');
            this.logout();
            return;
          }
          
          this.user = JSON.parse(userString);
          this.token = token;
          this.isAuthenticated = true;
          this.expiresAt = expiresAt;
        } catch (e) {
          console.error('解析存储用户数据失败', e);
          this.logout();
        }
      }
    }
  }
}); 